package com.zhx.sweet.authentication.encrypt;

import com.zhx.sweet.encrypt.EncryptUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * 配置加密登录注册到springsecurity的过滤链中去
 *
 * @author zhx
 * @create 2018年06月30日16:01:15
 **/
@Component
public class EncryptAuthenticationConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain,HttpSecurity> {
    //注入自定义的成功处理器
    @Autowired
    private AuthenticationSuccessHandler authentionSuccessHandler;

    //注入自定义的失败处理器
    @Autowired
    private AuthenticationFailureHandler authentionFailedHandler;

    @Autowired(required = false)
    private EncryptUserDetailService encryptUserDetailService;


    @Override
    public void configure(HttpSecurity http) throws Exception {
        if(encryptUserDetailService != null){
            //注册过滤器
            EncryptAuthenticationFilter encryptAuthenticationFilter = new EncryptAuthenticationFilter();
            encryptAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
            encryptAuthenticationFilter.setAuthenticationSuccessHandler(authentionSuccessHandler);
            encryptAuthenticationFilter.setAuthenticationFailureHandler(authentionFailedHandler);

            EncryptAuthenticationProvider encryptAuthenticationProvider = new EncryptAuthenticationProvider();
            encryptAuthenticationProvider.setUserDetailsService(encryptUserDetailService);

            http.authenticationProvider(encryptAuthenticationProvider)
                    .addFilterAfter(encryptAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        }
    }
}
